package eu.fritschi.parachatcapture;

import java.io.IOException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import org.apache.log4j.Logger;


public class Settings {
	private static final Logger logger = Logger.getLogger(Settings.class);
	private static final String PARACHAT_HOST = "parachat.host";
	private static final String NETWORK_CAPTURE_DEVICE_ID = "network.capture.device.id";
	private static final String AUTHORS_FILTER = "authors.filter";
	private static final String DUMP_FILE = "dump.file";
	private static final Settings INSTANCE = new Settings();

	private String parachatHost;
	private int networkCaptureDeviceId;
	private final Set<String> authorsFilterSet = new HashSet<String>();
	private String dumpFile;

	private Settings() {}
	
	public static Settings getInstance() {
		return INSTANCE;
	}

	public void initialize() throws IOException {
		Properties properties = new Properties();
		properties.load(getClass().getClassLoader().getResourceAsStream("parachatcapture.properties"));

		parachatHost = properties.getProperty(PARACHAT_HOST);
		if (parachatHost == null || parachatHost.trim().equals("")) {
			String message = "Mandatory property " + PARACHAT_HOST + " is not defined.";
			logger.fatal(message);
			throw new RuntimeException(message);
		}

		String networkCaptureDeviceIdString = properties.getProperty(NETWORK_CAPTURE_DEVICE_ID);
		networkCaptureDeviceId = Integer.parseInt(networkCaptureDeviceIdString);
		
		authorsFilterSet.clear();
		String authorsFilterString = properties.getProperty(AUTHORS_FILTER);
		if (authorsFilterString != null) {
			String[] authors = authorsFilterString.split(",");
			for (String string : authors) {
				if (!string.trim().equals("")) {
					authorsFilterSet.add(string);
				}
			}
		}
		
		dumpFile = properties.getProperty(DUMP_FILE);
	}
	
	public String getParachatHost() {
		return parachatHost;
	}
	
	public int getNetworkCaptureDeviceId() {
		return networkCaptureDeviceId;
	}
	
	public boolean processMessage(ParachatMessage parachatMessage) {
		if (authorsFilterSet.isEmpty()) {
			// No filter defined -> all messages are 
			return true;
		}
		
		return authorsFilterSet.contains(parachatMessage.getAuthor());
	}
	
	public String getDumpFile() {
		return dumpFile;
	}

	@Override
	public String toString() {
		return "Settings [parachatHost=" + parachatHost
				+ ", networkCaptureDeviceId=" + networkCaptureDeviceId
				+ ", authorsFilterSet=" + authorsFilterSet + ", dumpFile="
				+ dumpFile + "]";
	}
}